const { Users } = require('../utils/db')

// 创建用户
const createUser = (userInfo, file = {}) => {
  const users = new Users({
    username: userInfo.username,
    sex: userInfo.sex,
    age: userInfo.age,
    password: userInfo.password,
    createTime: new Date().getTime(),
    userPhoto: {
      path: file.filename && `http://localhost:3000/static/uploads/${file.filename}`,
      filename: file.originalname
    }
  });
  return users.save()
}

// 删除用户
const deleteUser = (id) => {
  return Users.remove({ _id: id }, { single: true })
}

// 修改用户
const editUser = async (userInfo) => {
  const user = await Users.findOne({ _id: userInfo.id })
  user.set({
    username: userInfo.username,
    sex: userInfo.sex,
    age: userInfo.age,
    password: userInfo.password,
    modifyTime: new Date().getTime()
  })

  return user.save()
}

const getTotal = (query) => {
  return Users.find(query)
}

// 获取用户列表
const getUserList = async (query, body) => {
  return Users.find(query)
    .skip((body.curPage - 1) * body.pageSize)
    .limit(parseInt(body.pageSize) || 20)
    .sort({ createTime: body.sort })
    .select({
      _id : 1,
      username: 1,
      sex: 1,
      age: 1,
      createTime: 1,
      modifyTime: 1
    })
}

// 查询单个用户ByUsername
const findOneUser = (username) => {
  return Users.findOne({ username })
}

// 查询单个用户ById
const findUserById = (id) => {
  return Users.findById(id )
}

module.exports = {
  createUser,
  deleteUser,
  editUser,
  getTotal,
  getUserList,
  findOneUser,
  findUserById,
}
